package com.sduept.nwld.dataserver.controller.equipment.assessment;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.TreeNode;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.document.entity.core.RecordImage;
import com.sduept.bigdata.document.enums.AttachmentType;
import com.sduept.bigdata.equipment.assessment.enums.ItemTypeEnum;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionExpert;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionItem;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionQuestionEquipment;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionQuestionEquipmentFeedback;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionStation;
import com.sduept.bigdata.equipment.assessment.service.InspectionDocumentService;
import com.sduept.bigdata.equipment.assessment.service.InspectionExpertService;
import com.sduept.bigdata.equipment.assessment.service.InspectionItemService;
import com.sduept.bigdata.equipment.assessment.service.InspectionQuestionEquipmentService;
import com.sduept.bigdata.equipment.assessment.service.InspectionStationService;
import com.sduept.bigdata.equipment.assessment.service.RectificationPlanService;
import com.sduept.bigdata.equipment.assessment.service.impl.DeductionTaskService;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.manager.PersonnelManager;
import com.sduept.utils.Base64;

/**
 * @author laiy
 * @Date 2019年11月10日 变电站检查扣分视图
 */
@Named
@ViewScoped
public class InspectionStationDeductController extends AbstractController {

	/**
	 * @author laiy
	 * @Date 2019年11月10日
	 */

	private static final long serialVersionUID = -2590264374125346155L;
	@Autowired
	private CommonDocumentProperties pros;
	@Autowired
	private PersonnelManager pm;
	@Autowired
	private InspectionDocumentService docService;
	@Autowired
	private DeductionTaskService service;
	@Autowired
	private InspectionQuestionEquipmentService quesEquipmentService;
	@Autowired
	private InspectionExpertService expertService;
	@Autowired
	private InspectionItemService itemService;
	@Autowired
	private InspectionStationService inspectionStationService;
	@Autowired
	private RectificationPlanService trackService;
	 
	
	/**
	 * 传递的参数：评价厂站id
	 */
	private String inspectionStationId;
	/**
	 * 传递的参数：是否可评价该厂站
	 */
	private boolean editable;
	/**
	 * 评价的厂站
	 */
	private InspectionStation currentInspectionStation;

	private InspectionItem inspectionItemRoot;

	private int totalItemCount;
	private int finishedItemCount;
	/**
	 * 无需评价的条目数量
	 */
	private int nocheckItemCount;

	// 评价变电站数据展示table模型集合
	private List<InspStationTableModel> selectLists = new ArrayList<>();
	private List<InspStationTableModel> selectAll = new ArrayList<>();
	private List<InspStationTableModel> finishedSelect = new ArrayList<>();
	private List<InspStationTableModel> unFinishedSelect = new ArrayList<>();
	private String statusTitle;
	/**
	 * 设限总扣分
	 */
	private float deductPointsTotal = 0.0f;
	/**
	 * 实际总扣分
	 */
	private float realPointsTotal = 0.0f;

	private TreeNode itemRoot;
	private TreeNode[] selectedItemNodes;
	private int status;
	
//	private List<FeedbackDTO> focusedQuesEquipmentFeedbacks = new ArrayList<FeedbackDTO>();
	private com.sduept.bigdata.document.dto.RecordImageDTO newImageDto;
	
	private boolean feedbackViewEditable;
	//被检单位联系人登录
	private boolean stationPersonnelLogin;
	private InspStationTableModel focusedModel;
	private List<InspectionItem> inspectionCriterionAll = new ArrayList<InspectionItem>();
	
	//当前登录的专家
	private InspectionExpert currentExpert;
	@PostConstruct
	public void init() {
		try {
			initParamters();
			// 获得当前展示的评价变电站
			currentInspectionStation = service.getInspectionStationById(inspectionStationId);
			if(getCurrentUser().getName().equals(currentInspectionStation.getStationPersonnel())) {
				stationPersonnelLogin = true;
			}
			// 实际总扣分
			realPointsTotal = currentInspectionStation.getRealDeduct() == null ? 0
					: currentInspectionStation.getRealDeduct();
			// 设限总扣分
			deductPointsTotal = currentInspectionStation.getDeduct() == null ? 0 : currentInspectionStation.getDeduct();
			if (editable) {
				if (currentInspectionStation.getActualStartTime() == null) {
					currentInspectionStation.setActualStartTime(new Date());
				}
				//获得当前登录的专家
				currentExpert = expertService.findByCode(getCurrentUser().getCode());
			}
			
			initData();
//			List<InspectionItem> inspectionCriterionAll = service.getInspectionItems(inspectionStationId);
			initSelectLists(inspectionCriterionAll);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initSelectLists(List<InspectionItem> inspectionItems) {
		Map<InspectionItem,InspectionQuestionEquipmentFeedback> itemAndFeedbackMap = new HashMap<InspectionItem, InspectionQuestionEquipmentFeedback>();
		for(InspectionItem item : inspectionItems) {
			itemAndFeedbackMap.put(item, service.getInspectionQuestionEquipmentFeedback(inspectionStationId, item.getId()));
		}
		selectAll = InspStationTableModel.getListByInspectionCriterionAndFeedbackMap(itemAndFeedbackMap);
//		selectAll = InspStationTableModel.getListByInspectionCriterions(inspectionItems);
		if (selectAll != null && !selectAll.isEmpty()) {
			InspStationTableModel.sortModelList(selectAll);
			initFinishedAndUnFinishedSelect();
			selectLists = selectAll;
			status = 0;
			
		}
	}

	private void initFinishedAndUnFinishedSelect() {
		unFinishedSelect.clear();
		finishedSelect.clear();
		for (InspStationTableModel model : selectAll) {
			if (model.getStatus() == 0) {
				unFinishedSelect.add(model);
			} else {
				finishedSelect.add(model);
			}
		}
	}

	/**
	 * 生成评价条目树
	 */
	private void generateInspectionItemTree() {
		itemRoot = new LibTreeNode("Root", null);
		inspectionItemRoot = service.getInspectionItemRootNodeById(inspectionStationId);
		LibTreeNode itemNode = new LibTreeNode(inspectionItemRoot.getItemType().getValue(), inspectionItemRoot,
				itemRoot);
		try {
			addChildrenItemNode(inspectionItemRoot, itemNode);
		} catch (ParameterException e) {
			e.printStackTrace();
		}
		itemNode.setExpanded(true);
		itemRoot.setExpanded(true);
	}

	/**
	 * 添加评价项的子节点
	 * 
	 * @param pItem
	 * @param pItemNode
	 * @throws ParameterException
	 */
	private void addChildrenItemNode(InspectionItem pItem, LibTreeNode pItemNode) throws ParameterException {
		List<InspectionItem> items = service.getInspectionItemChildren(inspectionStationId, pItem.getId());
		if (items != null && !items.isEmpty()) {
			for (InspectionItem item : items) {
				LibTreeNode itemNode = new LibTreeNode(item.getItemType().getValue(), item, pItemNode);
				if (ItemTypeEnum.INSPECTIONITME.getValue().equals(item.getItemType().getValue())) {
					if (pItem.getStatus() == 0 && item.getStatus() == 1) {
						pItemNode.setExpanded(true);
					}
				} else if (ItemTypeEnum.INSPECTIONREQUIREMENT.getValue().equals(item.getItemType().getValue())) {
					if (pItem.getStatus() == 0 && item.getStatus() == 1) {
						pItemNode.setExpanded(true);
						pItemNode.getParent().setExpanded(true);
					}
				} else {
					if (pItem.getStatus() == 0 && item.getStatus() == 1) {
						pItemNode.setExpanded(true);
						pItemNode.getParent().setExpanded(true);
						pItemNode.getParent().getParent().setExpanded(true);
					}
				}
				addChildrenItemNode(item, itemNode);
			}
		}

	}

	/**
	 * 初始化参数信息
	 */
	private void initParamters() {
		inspectionStationId = getParameter("id");
		String isEditable = getParameter("isEditable");
		
		  if("true".equals(isEditable)) { editable = true; }
	}

	private void initData() {
		inspectionCriterionAll.clear();
		List<InspectionItem> inspectionAll = service.getInspectionItems(inspectionStationId);
		for (InspectionItem item : inspectionAll) {
			if(item.getItemType().equals(ItemTypeEnum.INSPECTIONCRITERION)) {
				inspectionCriterionAll.add(item);
				if (item.getStatus() == 1 && item.getDeductionCriteria() != 0) {
					finishedItemCount++;
				}
				if (item.getDeductionCriteria() == 0) {
					nocheckItemCount++;
				}
			}
		}
		totalItemCount = inspectionCriterionAll.size() - nocheckItemCount;
	}

	/**
	 * 页面左侧隐藏的菜单栏打开之前处理函数
	 */
	public void beforeOpenSideBar() {
		if (itemRoot == null) {
			generateInspectionItemTree();
		}
	}

	/**
	 * 通过选中的评价条目节点展示对应的模型
	 */
	public void showSelectedNodeToModel() {
		if (selectedItemNodes.length > 0) {
			List<InspStationTableModel> selects = new ArrayList<InspStationTableModel>();
			for (int i = 0; i < selectedItemNodes.length; i++) {
				if ("INSPECTIONCRITERION".equals(selectedItemNodes[i].getType())) {
					InspectionItem item = (InspectionItem) selectedItemNodes[i].getData();
					for (InspStationTableModel model : selectAll) {
						if (item.getId().equals(model.getInspectionItemId())) {
							selects.add(model);
						}
					}
				}
			}
			selectLists = selects;
			statusTitle = "";
		} else {
			if (StringUtils.isBlank(statusTitle)) {
				selectLists = new ArrayList<InspStationTableModel>();
			}
		}

	}

	/**
	 * 根据状态展示评价项
	 */
	public void queryByStatus() {
		switch (status) {
		case 0:
			selectLists = selectAll;
			statusTitle = "【全部】";
			break;
		case 1:
			initFinishedAndUnFinishedSelect();
			selectLists = finishedSelect;
			statusTitle = "【已完成】";
			break;
		case 2:
			initFinishedAndUnFinishedSelect();
			selectLists = unFinishedSelect;
			statusTitle = "【未完成】";
			break;
		default:
			break;
		}
	}

	/**
	 * 将该评价项设置为已完成
	 * 
	 * @param model
	 */
	public void setItemFinished(InspStationTableModel model) {
		InspectionItem inspectionItem = service.getInspectionItemById(inspectionStationId,model.getInspectionItemId());
		if (inspectionItem != null) {// 将该评价条目的状态设置为已完成
			inspectionItem.setStatus(1);
			inspectionItem.setActualAssessmentExpertId(currentExpert.getId());
			inspectionItem.setActualAssessmentExpertName(currentExpert.getName());
			// 判断父节点是否设置为已完成
			setParentToFinished(inspectionItem);
			itemService.update(inspectionItem);
			model.setStatus(1);
			finishedItemCount++;
		} else {
			System.err.println("缓存和数据库中都未找到该评价对象");
		}

	}

	/**
	 * 设置父评价条目为已完成
	 * 
	 * @param item
	 */
	private void setParentToFinished(InspectionItem item) {
		if (settableParentToFinished(item)) {
			InspectionItem parent = item.getParent();
			parent.setStatus(1);
			setParentToFinished(parent);
		}
	}

	/**
	 * 判断父节点是否可以设置为已完成 条件：该父节点下的所有子评价条目都已完成
	 * 
	 * @param item
	 * @return
	 */
	private boolean settableParentToFinished(InspectionItem item) {
		InspectionItem parent = item.getParent();
		if (parent != null) {
			List<InspectionItem> children = service.getInspectionItemChildren(inspectionStationId,item.getId());
			for (InspectionItem child : children) {
				if (child.getStatus() == 0) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * 保存
	 */
//	public void save() {
//		for (InspStationTableModel model : selectLists) {
//			if (model.isSave()) {
//				InspectionItem inspectionItem = service.getInspectionItemById(inspectionStationId,model.getInspectionItemId());
//				inspectionItem.setStatus(1);
//				service.update(inspectionItem);
//				setParentToFinished(inspectionItem);
//			}
//		}
//		service.update(currentInspectionStation);
//		PrimeFaces.current().executeScript("close('save')");
//	}

	/**
	 * 提交评价信息，提交完成后该评价厂站的状态将置为已完成 只需将评价厂站的状态置为已完成
	 */
	public void submit() {
		currentInspectionStation = service.getInspectionStationById(currentInspectionStation.getId());
		currentInspectionStation.setStatus(2);
		currentInspectionStation.setActualEndTime(new Date());
		inspectionStationService.update(currentInspectionStation);
		String mark = "submit-" + currentInspectionStation.getId();
		PrimeFaces.current().executeScript("close('" + mark + "')");
	}

	/**
	 * 计算未完成评价数
	 * 
	 * @return
	 */
	public int getUnFinishedCount() {
		int count = 0;
		for (InspStationTableModel model : selectLists) {
			if (model.getStatus() == 0 && model.getDeductionCriteria() != 0) {
//				if (!model.isSave()) {
				count++;
//				}
			}
		}
		return count;
	}

	/**
	 * 获得评价时间字符串
	 * 
	 * @return
	 */
	public String getInspectionTimeStr() {
		String result = currentInspectionStation.getInspectPlan().getStartTime().toString().substring(0, 10) + "至"
				+ currentInspectionStation.getInspectPlan().getEndTime().toString().substring(0, 10);
		return result;

	}

	/**
	 * 重构扣分类测试 DefaultDeductionService
	 */
	public void onEquipmentDialogReturn() {
		int index = Integer.parseInt(getParameter("index"));
		// 获得当前扣分的model
		InspStationTableModel model = selectLists.get(index);
		if (model.getStatus() != 1) {// 将该项状态设置为已完成
			model.setStatus(1);
			finishedItemCount++;
		}
		try {
			// 1.计算该项当前扣分值
			List<InspectionQuestionEquipment> quesEquipments = quesEquipmentService
					.findByInspectionItem(model.getInspectionItemId());
			model.setQuestionEquipments(quesEquipments);
			float quesDeduct = 0.0f;
			if (!quesEquipments.isEmpty()) {
				for (InspectionQuestionEquipment quesEquipment : quesEquipments) {
					quesDeduct += quesEquipment.getQuesDeduct();
				}
			}
//			service.getInspectionItemById(inspectionStationId, model.getInspectionItemId()).setQuestionEquipments(quesEquipments);
			InspectionItem inspectionItem = service.getInspectionItemById(inspectionStationId, model.getInspectionItemId());
			inspectionItem.setQuestionEquipments(quesEquipments);
			
			if(null != currentExpert) {
				inspectionItem.setActualAssessmentExpertId(currentExpert.getId());
				inspectionItem.setActualAssessmentExpertName(currentExpert.getName());
			} else {
				inspectionItem.setActualAssessmentExpertName(getCurrentUser().getName());
			}
			service.doDeduction(inspectionStationId, model.getInspectionItemId(), quesDeduct);
			updateRequirementDeductOfModel(model.getInspectionId());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新指定检查要素及要求的model的requirementDeduct
	 * 
	 * @param requirementId
	 */
	private void updateRequirementDeductOfModel(String requirementId) {
		InspectionItem requirement = service.getInspectionItemById(inspectionStationId,requirementId);
		for (InspStationTableModel model : selectAll) {
			if (model.getInspectionId().equals(requirementId)) {
				model.setRequirementDeduct(requirement.getDeduct());
				model.setRiskLevel(requirement.getRealRiskLevel());
			}
		}
	}


	/**
	 * 处理问题描述和整改建议改变事件
	 * 
	 * @param model
	 */
	public void onRemarkerBlur(InspStationTableModel model) {
		InspectionItem inspectionItem = service.getInspectionItemById(inspectionStationId,model.getInspectionItemId());
		inspectionItem.setProblemDescription(model.getProblemDescription());
		inspectionItem.setRecommendation(model.getRecommendation());
		if(null != currentExpert) {
			inspectionItem.setActualAssessmentExpertId(currentExpert.getId());
			inspectionItem.setActualAssessmentExpertName(currentExpert.getName());
		} else {
			inspectionItem.setActualAssessmentExpertName(getCurrentUser().getName());
		}
		itemService.update(inspectionItem);
	}

	/**
	 * 将未评价的项设置完成后提交
	 */
	public void setItemFinishedAutomatically() {
		for (InspStationTableModel model : selectLists) {
			if (model.getStatus() == 0) {
				setItemFinished(model);
				if (model.getDeductionCriteria() == 0) {
					finishedItemCount--;
				}
			}
		}
		submit();
	}

	public void onFeedbackBlur(InspStationTableModel model) {
		InspectionQuestionEquipmentFeedback feedback = service.getInspectionQuestionEquipmentFeedback(inspectionStationId, model.getInspectionItemId());
		if(feedback==null) {
			feedback = new InspectionQuestionEquipmentFeedback();
			feedback.setId(ObjectId.get().toString());
			feedback.setPlanId(currentInspectionStation.getInspectPlan().getId());
			feedback.setInspectionStationId(inspectionStationId);
			feedback.setInspectionItemId(model.getInspectionItemId());
			feedback.setFeedbackPersonnel(getCurrentUser().getName());
			feedback.setFeedbackPersonnelPhone(getCurrentUser().getTelephone());
		}
		feedback.setFeedback(model.getFeedback());
		service.createInspectionQuestionEquipmentFeedback(inspectionStationId, feedback);
	}
	//
	public void preUploadImage() {
		InspectionQuestionEquipmentFeedback feedback = service.getInspectionQuestionEquipmentFeedback(inspectionStationId, focusedModel.getInspectionItemId());
		if(feedback==null) {
			feedback = new InspectionQuestionEquipmentFeedback();
			feedback.setId(ObjectId.get().toString());
			feedback.setPlanId(currentInspectionStation.getInspectPlan().getId());
			feedback.setInspectionStationId(currentInspectionStation.getId());
			feedback.setInspectionItemId(focusedModel.getInspectionItemId());
			feedback.setFeedbackPersonnel(getCurrentUser().getName());
			feedback.setFeedbackPersonnelPhone(getCurrentUser().getTelephone());
			service.createInspectionQuestionEquipmentFeedback(inspectionStationId, feedback);
		}
//		newImageDtos = equipmentAndNewImageMap.get(qe);
//		if(null == newImageDtos) {
//			newImageDto = new RecordImageDTO();
//		}
		newImageDto =  new com.sduept.bigdata.document.dto.RecordImageDTO();
		newImageDto.setId(ObjectId.get().toString());
		newImageDto.setOid(feedback.getId());
		PersonnelEntityBean user = getCurrentUser();
		if(null != user) {
			newImageDto.setCreator(user.getCode());
		}
	}
	/**
	 * 上传图片
	 * @param event
	 */
	public void handleImageFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String fileName = file.getFileName();
		byte[] content = file.getContents();
		String imageContents = new String(Base64.encodeBytes(content));
		newImageDto.setImageStr(imageContents);
		newImageDto.setName(fileName);
		newImageDto.setType(AttachmentType.PICTURE);
		try {
			docService.upload(newImageDto);
			addSuccessMessage("上传成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}
		findFeedbackImagesByItem(focusedModel);
		PrimeFaces.current().ajax().update(Arrays.asList("feedbackViewForm"));
	}
	/**
	 * 上传视频
	 * @param event
	 */
	public void handleVideoFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String fileName = file.getFileName();
		byte[] content = file.getContents();
		String imageContents = new String(Base64.encodeBytes(content));
		newImageDto.setImageStr(imageContents);
		newImageDto.setName(fileName);
		newImageDto.setType(AttachmentType.VIDEO);
		try {
			docService.upload(newImageDto);
			addSuccessMessage("上传成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}
		newImageDto = new  com.sduept.bigdata.document.dto.RecordImageDTO();
		findFeedbackVideosByItem(focusedModel);
		PrimeFaces.current().ajax().update(Arrays.asList("feedbackVideoForm"));
	}
	/**
	 * 图片地址集合
	 */
	private List<String> imagePaths;
	private Map<String, RecordImage> recordImageMap;
	/**
	 * 查找图片
	 * 
	 * @param item
	 */
	public void findImagesByItem(InspStationTableModel item) {
		imagePaths = new ArrayList<String>();
		List<RecordImage> allImages = new ArrayList<RecordImage>();
		try {
			// 通过item获取问题设备
			List<InspectionQuestionEquipment> equipments = item.getQuestionEquipments();
			for (InspectionQuestionEquipment equipment : equipments) {
				allImages.addAll(docService.findRecordImageIdByOid(equipment.getId()));
			}
			String dir = docService.findCommonImagePath();
			for (RecordImage i : allImages) {
				if (AttachmentType.PICTURE.equals(i.getType())) {
					imagePaths.add(dir + '/' + i.getPath());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("查找问题设备的图片出错");
		}
	}
	
	public void findFeedbackImagesByItem(InspStationTableModel item) {
		imagePaths = new ArrayList<String>();
		recordImageMap = new HashMap<String, RecordImage>();
		feedbackViewEditable = false;
		focusedModel = item;
		// 通过itemId查找问题设备
		String dir = docService.findCommonImagePath();
		InspectionQuestionEquipmentFeedback feedback = service.getInspectionQuestionEquipmentFeedback(inspectionStationId, item.getInspectionItemId());
		try {
			if(feedback!=null) {
				List<RecordImage> images = docService.findRecordImageIdByOid(feedback.getId());
				for (RecordImage i : images) {
					if (AttachmentType.PICTURE.equals(i.getType())) {
						imagePaths.add(dir + '/' + i.getPath());
						recordImageMap.put(dir + '/' + i.getPath(), i);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("查找问题设备的图片出错");
		}
	}
	/**
	 * 视频集合
	 */
	private List<RecordImageDTO> videoDTOs;
	private DefaultStreamedContent file;
	/**
	 * 查找视频
	 * 
	 * @param item
	 */
	public void findVideosByItem(InspStationTableModel item) {
		videoDTOs = new ArrayList<RecordImageDTO>();
		// 通过itemId查找问题设备
		List<InspectionQuestionEquipment> equipments = item.getQuestionEquipments();

		PersonnelEntityBean p = null;
		for (InspectionQuestionEquipment equipment : equipments) {
			try {
				List<RecordImage> images = docService.findRecordImageIdByOid(equipment.getId());
				for (RecordImage i : images) {
					if (AttachmentType.VIDEO.equals(i.getType())) {
						p = pm.findPersonnelByCode(i.getCreator());
						RecordImageDTO dto = new RecordImageDTO();
						dto.setEquipment(equipment);
						dto.setRecord(i);
						if (null != p) {
							dto.setCreaterName(p.getName());
						}
						videoDTOs.add(dto);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage("查找问题设备的视频出错");
			}
		}
	}
	//
	public void findFeedbackVideosByItem(InspStationTableModel item) {
		videoDTOs = new ArrayList<RecordImageDTO>();
		focusedModel = item;
		// 通过itemId查找问题设备
		PersonnelEntityBean p = null;
		try {
			InspectionQuestionEquipmentFeedback feedback = service.getInspectionQuestionEquipmentFeedback(inspectionStationId, item.getInspectionItemId());
			if(feedback!=null) {
				List<RecordImage> images = docService.findRecordImageIdByOid(feedback.getId());
				for (RecordImage i : images) {
					if (AttachmentType.VIDEO.equals(i.getType())) {
						p = pm.findPersonnelByCode(i.getCreator());
						RecordImageDTO dto = new RecordImageDTO();
						dto.setRecord(i);
						if (null != p) {
							dto.setCreaterName(p.getName());
						}
						videoDTOs.add(dto);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("查找问题设备的视频出错");
		}
	}
	/**
	 * 下载视频到本地
	 * 
	 * @param record
	 */
	public void downLoadVideo(RecordImage record) {
		try {
			String content = docService.downloadOriginalById(record.getId());
			byte[] b = Base64.decode(content);
			String outFilePath = pros.getExportTempPath()+record.getName();
			FileOutputStream ous = new FileOutputStream(new File(outFilePath));
			ous.write(b);
			ous.close();
			addSuccessMessage("下载成功，视频地址："+outFilePath);
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("下载失败");
		}
	}
	
	/**
	 * 删除视频
	 * 
	 * @param record
	 */
	public void deleteRecordImage(RecordImageDTO recordDto) {
		try {
			docService.deleteImageByid(Arrays.asList(recordDto.getRecord().getId()));
			addSuccessMessage("删除视频成功");
			videoDTOs.remove(recordDto);
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("删除视频失败");
		}
	}
	/**
	 * 是否编辑反馈图片
	 * @param i
	 */
	public void editFeedbackView(int i) {
		if(i==0) {
			feedbackViewEditable = true;
		}else {
			feedbackViewEditable = false;
		}
		
	}
	public void deleteByImagePath(String image) {
		RecordImage record = recordImageMap.get(image);
		try {
			docService.deleteImageByid(Arrays.asList(record.getId()));
			imagePaths.remove(image);
			addSuccessMessage("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class RecordImageDTO {
		private RecordImage record;
		private InspectionQuestionEquipment equipment;
		private String createrName;

		public RecordImage getRecord() {
			return record;
		}

		public void setRecord(RecordImage record) {
			this.record = record;
		}

		public InspectionQuestionEquipment getEquipment() {
			return equipment;
		}

		public void setEquipment(InspectionQuestionEquipment equipment) {
			this.equipment = equipment;
		}

		public String getCreaterName() {
			return createrName;
		}

		public void setCreaterName(String createrName) {
			this.createrName = createrName;
		}

	}

	public InspectionStation getCurrentInspectionStation() {
		return currentInspectionStation;
	}

	public void setCurrentInspectionStation(InspectionStation currentInspectionStation) {
		this.currentInspectionStation = currentInspectionStation;
	}

	public List<InspStationTableModel> getSelectLists() {
		return selectLists;
	}

	public void setSelectLists(List<InspStationTableModel> selectLists) {
		this.selectLists = selectLists;
	}

	public float getDeductPointsTotal() {
		return deductPointsTotal;
	}

	public void setDeductPointsTotal(float deductPointsTotal) {
		this.deductPointsTotal = deductPointsTotal;
	}

	public boolean isEditable() {
		return editable;
	}

	public void setEditable(boolean editable) {
		this.editable = editable;
	}

	public String getStatusTitle() {
		return statusTitle;
	}

	public void setStatusTitle(String statusTitle) {
		this.statusTitle = statusTitle;
	}

	public int getTotalItemCount() {
		return totalItemCount;
	}

	public void setTotalItemCount(int totalItemCount) {
		this.totalItemCount = totalItemCount;
	}

	public int getFinishedItemCount() {
		return finishedItemCount;
	}

	public void setFinishedItemCount(int finishedItemCount) {
		this.finishedItemCount = finishedItemCount;
	}

	public TreeNode getItemRoot() {
		return itemRoot;
	}

	public void setItemRoot(TreeNode itemRoot) {
		this.itemRoot = itemRoot;
	}

	public TreeNode[] getSelectedItemNodes() {
		return selectedItemNodes;
	}

	public void setSelectedItemNodes(TreeNode[] selectedItemNodes) {
		this.selectedItemNodes = selectedItemNodes;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public float getRealPointsTotal() {
		return realPointsTotal;
	}

	public void setRealPointsTotal(float realPointsTotal) {
		this.realPointsTotal = realPointsTotal;
	}

	public List<String> getImagePaths() {
		return imagePaths;
	}

	public void setImagePaths(List<String> imagePaths) {
		this.imagePaths = imagePaths;
	}

	public List<RecordImageDTO> getVideoDTOs() {
		return videoDTOs;
	}

	public void setVideoDTOs(List<RecordImageDTO> videoDTOs) {
		this.videoDTOs = videoDTOs;
	}

	public DefaultStreamedContent getFile() {
		return file;
	}

	public void setFile(DefaultStreamedContent file) {
		this.file = file;
	}
	
	public boolean isFeedbackViewEditable() {
		return feedbackViewEditable;
	}

	public void setFeedbackViewEditable(boolean feedbackViewEditable) {
		this.feedbackViewEditable = feedbackViewEditable;
	}

	public boolean isStationPersonnelLogin() {
		return stationPersonnelLogin;
	}

	public void setStationPersonnelLogin(boolean stationPersonnelLogin) {
		this.stationPersonnelLogin = stationPersonnelLogin;
	}

}